<?php
// +----------------------------------------------------------------------
// | 开源协议 ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------

namespace app\mall\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\mall\model\Store as StoreModel;
use app\mall\model\Merch as MerchModel;
use util\Tree;
use think\facade\Env;
use think\facade\Db;

/**
 * 发货仓控制器
 * @package app\life\admin
 */
class Store extends Admin
{
    /**
     * 发货仓列表
     * @return mixed
     * @throws \think\Exception
     */
    public function index()
    {
        // 查询
        $map = $this->getMap();
        // 数据列表
		$order = $this->getOrder('id asc');
		$data_list = StoreModel::pageList($map, $order);
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setSearch(['title' => '发货仓名称']) // 设置搜索框
            ->addColumns([ // 批量添加数据列
               ['id', 'ID'],
               ['title', '名称', 'callback', function($value, $data){
                   return isset($data['title_prefix']) ? $data['title_display'] : $value;
               }, '__data__'],
			   // ['type', '类型', 'status', '', StoreModel::type()],
			   // ['nums', '库存管理',  'link' , url('life/stock/index', ['eid' => '__id__']), '_blank', 'pop', '库存管理'],
			   ['name', '发货人', 'text'],
			   ['mobile', '手机号', 'text'],
               ['sort', '排序', 'text.edit'],
               ['status', '状态', 'switch'],
               ['right_button', '操作', 'btn']
            ])
            ->addTopButtons('add,enable,disable') // 批量添加顶部按钮
            ->addRightButton('edit') // 添加右侧按钮
            ->addRightButton('delete', ['data-tips' => '删除发货仓?']) // 添加右侧按钮
            ->setRowList($data_list) // 设置表格数据
			//->hideColumn($hidden)
            ->fetch(); // 渲染模板
    }

    /**
     * 新增发货仓
     * @return mixed
     * @throws \think\Exception
     */
    public function add()
    {
        // 保存数据
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();

            // 验证
            $result = $this->validate($data, 'Store');
            if(true !== $result) $this->error($result);
			
			// 处理仓管ID
			if (!empty($data['uid']) && $data['uid'] != '') {
			    $data['uid'] = implode(',', $data['uid']);
			} else {
			    $data['uid'] = '';
			}
			
            if ($store = StoreModel::create($data)) {
                cache('store_list', null);
                // 记录行为
                action_log('store_add', 'mall_store', $store['id'], UID, $data['name']);
                $this->success('新增成功', 'index');
            } else {
                $this->error('新增失败');
            }
        }
		
        // 显示添加页面
        return ZBuilder::make('form')
			->addGroup([
				'基本设置' =>[
					['text', 'title', '发货仓名称', '<span class="text-danger">必填</span>'],
					['select', 'merch', '关联商户', '', MerchModel::getColumn(), 1],
					// ['radio', 'type', '类型', '', StoreModel::type(), 1],
					['text', 'name', '发货人', '<span class="text-danger">必填</span>'],
					['text', 'mobile', '手机号', '<span class="text-danger">必填</span>'],
					['text:3', 'province', '省份', '<span class="text-danger">必填</span>'],
					['text:3', 'city', '市', '<span class="text-danger">必填</span>'],
					['text:3', 'country', '区', '<span class="text-danger">必填</span>'],
					['text', 'address', '详细地址', '<span class="text-danger">必填</span>'],
					['radio', 'status', '立即启用', '', ['否', '是'], 1],
					['text', 'sort', '排序', '', 100],
				],
			])
            ->setTrigger('type', '1', 'url,target')
            ->fetch();
    }

    /**
     * 编辑发货仓
     * @param string $id 发货仓id
     * @return mixed
     * @throws \think\Exception
     */
    public function edit($id = '')
    {
        if ($id === 0) $this->error('参数错误');

        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();

            // 验证
            $result = $this->validate($data, 'Store');
            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);
			
			//扩展配置
			if(isset($data['ext_config'])) $data['ext_config'] = json_encode(parse_attr($data['ext_config']));
			// 处理仓管ID
			if (isset($data['uid'])) {
			    $data['uid'] = implode(',', $data['uid']);
			} else {
			    $data['uid'] = '';
			}

            if (StoreModel::update($data)) {
                // 记录行为
                action_log('store_edit', 'mall_store', $id, UID, $data['name']);
				cache('store_info_'. $id, null);
				cache('store_list', null);
                $this->success('编辑成功', 'index');
            } else {
                $this->error('编辑失败');
            }
        }

        // 获取数据
        $info = StoreModel::find($id);
        // 显示编辑页面
        return ZBuilder::make('form')
			->addGroup([
				'基本设置' =>[
					['hidden', 'id'],
					['hidden', 'type'],
					['text', 'title', '发货仓名称', '<span class="text-danger">必填</span>'],
					['select', 'merch', '关联商户', '', MerchModel::getColumn(), 1],
					// ['radio', 'type', '类型', '', StoreModel::type()],
					['text', 'name', '发货人', '<span class="text-danger">必填</span>'],
					['text', 'mobile', '手机号', '<span class="text-danger">必填</span>'],
					['text:3', 'province', '省份', '<span class="text-danger">必填</span>'],
					['text:3', 'city', '市', '<span class="text-danger">必填</span>'],
					['text:3', 'country', '区', '<span class="text-danger">必填</span>'],
					['text', 'address', '详细地址', '<span class="text-danger">必填</span>'],
					['radio', 'status', '立即启用', '', ['否', '是']],
					['text', 'sort', '排序'],
				],
			])
			->setFormData($info)
            ->fetch();
    }

    /**
     * 删除发货仓
     * @param null $ids 发货仓id
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function delete($ids = null)
    {
        if ($ids === null) $this->error('参数错误');
        // 删除并记录日志
        $store = StoreModel::where('id', $ids)->column('title','id');
		$store_name = $store[$ids];
		cache('store_list', null);
        return parent::delete(['store_delete', 'mall_store', 0, UID, $store_name]);
    }

    /**
     * 启用发货仓
     * @param array $record 行为日志
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function enable($record = [])
    {
        return $this->setStatus('enable');
    }

    /**
     * 禁用发货仓
     * @param array $record 行为日志
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function disable($record = [])
    {
        return $this->setStatus('disable');
    }

    /**
     * 设置发货仓状态：删除、禁用、启用
     * @param string $type 类型：enable/disable
     * @param array $record
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function setStatus($type = '', $record = [])
    {
        $ids           = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
        $store_delete = is_array($ids) ? '' : $ids;
        $store_names  = StoreModel::where('id', 'in', $ids)->column('title');
		cache('store_list', null);
        return parent::setStatus($type, ['store_'.$type, 'mall_store', $store_delete, UID, implode('、', $store_names)]);
    }

    /**
     * 快速编辑
     * @param array $record 行为日志
     * @return mixed
     */
    public function quickEdit($record = [])
    {
        $id      = input('post.pk', '');
        $field   = input('post.name', '');
        $value   = input('post.value', '');
        $store  = StoreModel::where('id', $id)->value($field);
        $details = '字段(' . $field . ')，原值(' . $store . ')，新值：(' . $value . ')';
		// 清除缓存
		cache('store_list', null);
		cache('store_info_'. $id, null);
        return parent::quickEdit(['store_edit', 'mall_store', $id, UID, $details]);
    }
}
